<template>
    <div class="dialogueSlotAbility knowledge-container">
        <div class="container">
            <div class="header flexbetween mb20">
                <el-input v-model="searchInput" placeholder="请输入关键字搜索" size="small" style="width:200px;">
                    <span slot="suffix" class="iconfont icon-sousuo"></span>
                </el-input>
                <div class="iconBtn">
                    <el-tooltip effect="light" content="添加" placement="top" :enterable="false">
                        <span class="iconfont icon-tianjia" @click="addForm"></span>
                    </el-tooltip>
                </div>
            </div>
            <element-table :data="list" :columns="cloumns" :loading="tableLoading" :tableHeight="tableHeight" :pageNo="pageNo"
                           :pageSize="pageSize" :total="total" @changePageNo="changePageNo" @changePageSize="changePageSize">
            </element-table>
        </div>
        <!-- 表单 弹窗-->
        <el-dialog :title="formTitle" :visible.sync="formVisible" width="980px" @before-close="clearLabel">
            <el-form ref="form" :model="form" :rules="formRules" label-width="120px" style="width: 80%; margin: 0px auto">
                <el-form-item prop="abilityName" label-width="120px" label="组件名称">
                    <el-input v-model="form.abilityName" size="small" />
                </el-form-item>
                <el-form-item prop="desc" label-width="120px" label="简介" type="textarea">
                    <el-input v-model="form.desc" size="small" />
                </el-form-item>
                <el-form-item label="应用范围">
                    <el-radio-group v-model="form.applyScope" style="line-height: 50px">
                        <el-radio :label="1">参数校验规则</el-radio>
                        <el-radio :label="2">参数生成规则</el-radio>
                        <el-radio :label="3">词槽回滚规则</el-radio>
                        <el-radio :label="4">词槽锁定规则</el-radio>
                        <el-radio :label="5">词槽挂起规则</el-radio>
                        <el-radio :label="6">参数抽取规则 </el-radio>
                        <el-radio :label="7">确认生成规则</el-radio>
                        <el-radio :label="8">响应规则</el-radio>
                        <el-radio :label="9">会话退出规则</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="实现类型">
                    <el-radio-group v-model="form.implementMode">
                        <el-radio v-if="form.applyScope == 8" :label="1">转人工</el-radio>
                        <el-radio v-if="form.applyScope == 8" :label="2">第三方</el-radio>
                        <el-radio :label="3">定制处理类</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="定制处理类" v-if="form.implementMode == 3">
                    <el-button @click="selectPyFile" size="small" type="primary">上传.py插件</el-button>
                    <input @change="upLoadPyPlugin" type="file" style="display: none" ref="pyfile" accept="text/x-python-script"
                           id="pyfiles" />
                    <el-button style="margin-left: 15px" size="small" type="primary" v-show="codeDebug.pyName && form.id"
                               @click="codeViewShow = true">调试插件</el-button>
                    <!-- <div>插件标记符：<el-input v-model="form.abilityName" /></div> -->
                    <div>
                        <el-form-item style="margin-top: 20px" label-width="100px" label="插件类名：">
                            <el-input placeholder="插件类名使用英文全称" :disabled="true" v-model="codeDebug.pyName" size="small" />
                        </el-form-item>
                    </div>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">关闭</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="formVisible = false" size="small" type="text">取 消</el-button>
                <el-button type="primary" size="small" @click="formSubmit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 表单 弹窗-->
        <!-- codeMirror -->
        <el-dialog title="调试插件" :visible.sync="codeViewShow" width="980px">
            <el-form ref="form" label-position="left" label-width="120px" style="width: 80%; margin-left: 50px">
                <el-form-item prop="title" label-width="120px" label="请求参数：">
                    <el-row>
                        <el-col :span="21">
                            <section v-for="(value, index) in codeDebug.paramNames" :key="index">
                                <section>
                                    <el-row>
                                        <el-col :span="6">
                                            <el-input v-model="codeDebug.paramNames[index]" size="small" style="width: 100%"
                                                      placeholder="请输入参数名" clearable />
                                        </el-col>
                                        <el-col :span="1"> &nbsp;</el-col>
                                        <el-col :span="13">
                                            <el-input v-model="codeDebug.paramValues[index]" size="small" style="width: 100%"
                                                      placeholder="请输入参数值" clearable />
                                        </el-col>
                                        <el-col :span="4" v-if="index == 0">
                                            <el-button size="mini" type="primary" icon="el-icon-plus" plain
                                                       style="margin-left: 10px; margin-top: 6px" circle @click="addOption(index, '1')" />
                                        </el-col>
                                        <el-col :span="4" v-if="index != 0">
                                            <el-button type="danger" size="mini" icon="el-icon-delete" plain
                                                       style="margin-left: 10px; margin-top: 6px" circle @click="rmOption(index, '1')" />
                                        </el-col>
                                    </el-row>
                                </section>
                            </section>
                        </el-col>
                        <el-col :span="3" style="text-align: right">
                            <el-button @click="codeDebugSubmit" size="mini" type="primary">发送</el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item prop="title" label-width="120px" label="返回数据：">
                    <el-input type="textarea" v-model="codeDebug.response" />
                </el-form-item>
                <el-form-item prop="title" label-width="120px" label="代码：">
                    <codemirror v-if="codeViewShow" :options="codeMirrorOptions" :value="codeDebug.code"></codemirror>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="codeViewShow = false" size="small">关 闭</el-button>
            </span>
        </el-dialog>
        <!-- codeMirror -->
    </div>
</template>

<script>
// codemirror
import { codemirror } from "vue-codemirror-lite";
require("codemirror/mode/python/python");
import "codemirror/theme/base16-dark.css";
// codemirror
import elementTable from "@/components/elementTable";
import { getDialogueSlotAbilityList, addDialogueSlotAbility, editDialogueSlotAbility, delDialogueSlotAbility, debugDialogueSlotAbility } from "@/api/knowledge.js";
export default {
    name: "dialogueSlotAbility",
    data() {
        return {
            list: [],
            searchInput: "",
            formType: "add",
            formVisible: false,
            tableLoading: false,
            pageNo: 1,
            pageSize: 10,
            total: 0,
            cloumns: [{
                config: {
                    label: "能力组件名称",
                    prop: "abilityName"
                },
            }, {
                config: {
                    label: "操作",
                },
                render: (h, scope) => {
                    return (
                        <div class="operation">
                            <el-tooltip effect="light" content="编辑" placement="top" enterable={false}>
                                <span class="iconfont icon-bianjidaan" onClick={() => this.editForm(scope)}></span>
                            </el-tooltip>
                            <el-tooltip effect="light" content="删除" placement="top" enterable={false}>
                                <span class="iconfont icon-shanchu" onClick={() => this.delSubmit(scope.id)}></span>
                            </el-tooltip>
                        </div>
                    );
                },
            }],
            codeViewShow: false,
            //内容
            coverShow: true,
            customToolbar: [["image", "code-block", "bold", "italic", "underline"]],
            form: {
                abilityName: "",
                desc: "",
                status: 1,
                applyScope: "",
                implementMode: "",
            },
            formRules: {
                abilityName: [
                    { required: true, message: "请输入能力名称", trigger: "blur" },
                ],
            },
            codeMirrorOptions: {
                autoCloseBrackets: true,
                tabSize: 4,
                styleActiveLine: true,
                lineNumbers: true,
                line: true,
                mode: "python",
                theme: "base16-dark",
            },
            codeDebug: {
                code: ``,
                pyName: "",
                response: "",
                paramNames: [""],
                paramValues: [""],
            },
        }
    },
    created() {
        this.getList();
        this.oriForm = JSON.parse(JSON.stringify(this.form));
        this.oriCodeDebug = JSON.parse(JSON.stringify(this.codeDebug));
    },
    methods: {
        //列表
        getList() {
            this.tableLoading = true;
            var param = {
                pageNo: this.pageNo,
                pageSize: this.pageSize
            }
            getDialogueSlotAbilityList(param).then(resp => {
                this.tableLoading = false;
                if (resp.status == 0) {
                    var data = resp.data;
                    this.total = data.total;
                    this.list = data.dialogueList;
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        async formSubmit() {
            var isValid = await this.checkForm();
            if (!isValid) {
                return this.$antMessage.warning("请填写完整信息");
            }
            var param = JSON.parse(JSON.stringify(this.form));
            if (this.formType == "add") {
                delete param["_id"];
                delete param["id"];
                param.code = this.codeDebug.code;
                param.pyName = this.codeDebug.pyName;
                addDialogueSlotAbility(param).then(resp => {
                    if (resp.status == 0) {
                        this.$antMessage.success("添加成功");
                        this.pageNo = 1;
                        this.getList();
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            } else {
                param.code = this.codeDebug.code;
                param.pyName = this.codeDebug.pyName;
                editDialogueSlotAbility(param).then(resp => {
                    if (resp.status == 0) {
                        this.$antMessage.success("编辑成功");
                        this.pageNo = 1;
                        this.getList();
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            }
            this.formVisible = false;
        },
        checkForm() {
            var that = this;
            return new Promise(function (resolve, reject) {
                that.$refs["form"].validate((valid) => {
                    resolve(valid);
                });
            });
        },
        delSubmit(id) {
            this.$confirm("是否确定删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                delDialogueSlotAbility({ id: id }).then((resp) => {
                    if (resp.status == 0) {
                        this.$antMessage.success("删除成功");
                        this.pageNo = 1;
                        this.getList();
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            }).catch();
        },
        addForm() {
            this.formType = "add";
            this.form = JSON.parse(JSON.stringify(this.oriForm));
            this.codeDebug = JSON.parse(JSON.stringify(this.oriCodeDebug));
            this.formVisible = true;
        },
        editForm(data) {
            console.log('editForm data', data)
            this.formType = "edit";
            this.form = Object.assign({}, data);
            this.codeDebug = JSON.parse(JSON.stringify(this.oriCodeDebug));
            this.codeDebug.code = data.code;
            this.codeDebug.pyName = data.pyName;
            this.formVisible = true;
        },
        clearLabel() {
            this.labelName = "";
        },
        changePageSize(val) {
            this.pageSize = val;
            this.getList();
        },
        changePageNo(val) {
            this.pageNo = val;
            this.getList();
        },
        selectPyFile() {
            this.$refs.pyfile.dispatchEvent(new MouseEvent("click"));
        },
        upLoadPyPlugin() {
            const selectedFile = this.$refs.pyfile.files[0];
            this.codeDebug.pyName = selectedFile.name;
            let reader = new FileReader();
            reader.readAsText(selectedFile);
            reader.onload = (event) => {
                var resutlStr = event.target.result.toString();
                this.codeDebug.code = resutlStr;
                // console.log("upLoadPyPlugin resutlStr", resutlStr);
            };
        },
        addOption(index, type) {
            if (type === "1") {
                this.codeDebug.paramNames.push("");
                this.codeDebug.paramValues.push("");
            }
        },
        rmOption(index, type) {
            switch (type) {
                case "1":
                    this.codeDebug.paramNames.splice(index, 1);
                    this.codeDebug.paramValues.splice(index, 1);
                    break;

                default:
                    break;
            }
            this.$message.success("移除成功");
        },
        codeDebugSubmit() {
            var that = this;
            var params = {};
            for (var i = 0; i < that.codeDebug.paramNames.length; i++) {
                var name = that.codeDebug.paramNames[i];
                params[name] = that.codeDebug.paramValues[i];
            }
            params.ab_id = that.form.id;
            console.log("codeDebugSubmit params", params);
            that.showLoading("提交中...");
            debugDialogueSlotAbility(params).then(resp => {
                that.closeLoading();
                if (resp.status == 0) {
                    that.codeDebug.response = JSON.stringify(resp.data);
                    this.$antMessage.success("提交成功");
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        showLoading(text = "加载中...") {
            this.loading = this.$loading({
                lock: true,
                text: text,
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
            });
        },
        closeLoading() {
            if (this.loading) this.loading.close();
        },
    },
    computed: {
        formTitle() {
            return this.formType == "add" ? "添加组件" : "编辑组件";
        },
        tableHeight() {
            return document.body.clientHeight - 310;
        },
    },
    components: {
        elementTable,
        codemirror
    }
}
</script>

<style lang="scss">
</style>